package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.BaseUserDao;
import com.hhs.storage.dao.PersonalPlanDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.DateEasy;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static java.time.temporal.ChronoUnit.DAYS;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-01-13
 */
@Service
@Transactional
public class PersonalPlanServiceImpl extends ServiceImpl<PersonalPlanDao, PersonalPlan> implements PersonalPlanService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private ProjectPlanService projectPlanService;
    @Autowired
    private ProjectMemberService projectMemberService;
    @Resource
    private BaseRoleService roleService;
    @Resource
    private BaseUserService userService;
    @Resource
    private BaseDepartmentService departmentService;
    @Resource
    private TopicMessageService topicMessageService;
    @Resource
    private AttachmentListService attachmentListService;
    @Resource
    private BaseUserDao userDao;
    @Resource
    private PersonConfigService configService;
    @Resource
    private BaseLogsService baseLogsService;

    //个人计划不可修改的间隔天数
    private final static int UNMODIFY = 2;

    @Override
    public Map<String, Object> getAll(PersonalPlan personalPlan, InputParam inputParam) {
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        if (!StringUtils.isEmpty(inputParam.getMonth())) {//月份不为空，限制月份范围,按工作日期限制
            qw.ge("work_date", inputParam.getMonth() + "-01");
            qw.le("work_date", inputParam.getMonth() + "-31");
        }
        if (personalPlan.getWorkDate() != null) {//日期不为空，查询指定日期
            qw.eq("work_date", personalPlan.getWorkDate());
        }
        if (!StringUtils.isEmpty(personalPlan.getUserId())) {//用户id不为空，则查询指定用户，否则查询当前用户
            qw.eq("user_id", personalPlan.getUserId());
        } else {
            qw.eq("user_id", SysUtil.getLoginUserId(request));
        }
        if (personalPlan.getType() != null) {//查询类型条件
            if (personalPlan.getType() == 0) {//查询个人
                qw.in("type", 0, 2);
            }
            if (personalPlan.getType() == 1) {//查询个人
                qw.in("type", 1);
            }
        }
        if (!StringUtils.isEmpty(personalPlan.getProjectId())) {//项目id不为空，则查询指定项目
            qw.eq("project_id", personalPlan.getProjectId());
        }
        //按工作日期与开始时间 升序排序
        qw.orderByAsc("work_date", "start_time", "end_time");
        List<PersonalPlan> list = this.list(qw);
        for (int i = 0; i < list.size(); i++) {
            PersonalPlan temp = list.get(i);
            if (StringUtils.isNotEmpty(temp.getProjectId())) {
                ProjectPlan projectPlan = projectPlanService.getById(temp.getProjectId());
                temp.setProjectPlan(projectPlan);
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list);
        map.put("code", 1);
        return map;
    }

    /**
     * 查询指定时间访问内的空闲任务
     *
     * @param personalPlan
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> freeTable(PersonalPlan personalPlan, InputParam inputParam) {
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        if (!StringUtils.isEmpty(inputParam.getMonth())) {//月份不为空，限制月份范围,按工作日期限制
            qw.ge("work_date", inputParam.getMonth() + "-01");
            qw.le("work_date", inputParam.getMonth() + "-31");
        }
        if (personalPlan.getWorkDate() != null) {//日期不为空，查询指定日期
            qw.eq("work_date", personalPlan.getWorkDate());
        }
        qw.eq("type", 2);//只查询空闲
        //按工作日期与开始时间 升序排序
        qw.orderByAsc("work_date", "start_time");
        List<PersonalPlan> list = this.list(qw);
        for (int i = 0; i < list.size(); i++) {
            PersonalPlan temp = list.get(i);
            BaseUser user = userService.getById(temp.getUserId());
            temp.setUser(user);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list);
        map.put("code", 1);
        return map;
    }

    /**
     * 查询部门及子部门每日最新完成任务
     *
     * @param departIds
     * @param workDate
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> getDepartmentDailyPlan(String departIds, LocalDate workDate, InputParam inputParam) {
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("work_date", workDate);
        //查询部门相关用户
        String[] idArr = departIds.split(",");
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < idArr.length; i++) {
            idList.add("'" + idArr[i] + "'");
        }
        departIds = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
        qw.inSql("user_id", "SELECT user_id FROM base_department_user WHERE depart_id IN(" + departIds + ")");
        //排序
        qw.orderByDesc("complete_time");
        qw.orderByAsc("start_time");
        //分页查询
        Page<PersonalPlan> result = this.page(new Page<PersonalPlan>(
                inputParam.getPage(),
                inputParam.getSize()), qw);
        List<PersonalPlan> personalPlans = result.getRecords();
        Map<String, Object> map = new HashMap<String, Object>();
        //分组，只显示 一人一条
//        List<PersonalPlan> personalPlans=this.baseMapper.getDepartmentDailyPlan(idArr,workDate,inputParam);
        //填充用户和部门信息
        for (int i = 0; i < personalPlans.size(); i++) {
            PersonalPlan temp = personalPlans.get(i);
            //查询用户信息
            BaseUser user = userService.getById(temp.getUserId());
            temp.setUser(user);
            //查询用户部门信息
            List<BaseDepartment> departList = departmentService.findByUserId(user.getId());
            user.setDepartment(departList.get(0));
        }
        map.put("rows", personalPlans);
        map.put("total", result.getTotal());
        map.put("code", 1);
        return map;
    }

    /**
     * 查询关注的人每日任务
     *
     * @param workDate
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> getFollowUserDailyTable(LocalDate workDate, String groupId, InputParam inputParam) {

        String userId = SysUtil.getLoginUserId(request);//当前登录用户id
        //查询项目相关用户
        QueryWrapper<BaseUser> userQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(groupId)) {
            userQueryWrapper.inSql("id_", "SELECT follow_user_id FROM user_follow_list WHERE group_id='" + groupId + "' and  user_id='" + userId + "'");
        } else {
            userQueryWrapper.inSql("id_", "SELECT follow_user_id FROM user_follow_list WHERE user_id='" + userId + "'");
        }
        //按名字查询
        if (StringUtils.isNotEmpty(inputParam.getName())) {
            userQueryWrapper.like("name_", inputParam.getName());
        }
        userQueryWrapper.eq("status_", 1);
        userQueryWrapper.orderByAsc("order_num");//按序号排序
        //分页查询
        Page<BaseUser> result = userService.page(new Page<BaseUser>(
                inputParam.getPage(),
                inputParam.getSize()), userQueryWrapper);
        List<BaseUser> userList = result.getRecords();
        List<String> userIds = new ArrayList<>();//当前页所有用户id
        for (int i = 0; i < userList.size(); i++) {
            userIds.add(userList.get(i).getId());
        }
        long total = result.getTotal();
        //查询指定用户指定日期所有项目任务
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("work_date", workDate);
        if (userIds.size() > 0) {
            qw.in("user_id", userIds.toArray());
        } else {
            qw.isNull("user_id");
        }

        //排序
        qw.orderByAsc("start_time");
        qw.orderByDesc("complete_time");
        List<PersonalPlan> personalPlanList = this.list(qw);
        //给领导派发类型任务添加领导信息
        leaderPlanAddLeader(personalPlanList);
        //归类任务数据到用户
        for (int j = 0; j < personalPlanList.size(); j++) {
            PersonalPlan personalPlan = personalPlanList.get(j);
            for (int i = 0; i < userList.size(); i++) {
                BaseUser user = userList.get(i);
                if (user.getId().equals(personalPlan.getUserId())) {//任务归类到用户
                    user.getPersonalPlanList().add(personalPlan);
                    break;
                }
            }
        }
        //返回结果
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", userList);
        map.put("total", total);
        map.put("code", 1);
        return map;
    }

    /**
     * 查询项目所有用户每人每日的所有任务
     *
     * @param projectId  项目id
     * @param workDate
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> getProjectDailyTable(String projectId, LocalDate workDate, InputParam inputParam) {
        //查询项目相关用户
        QueryWrapper<BaseUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.inSql("id_", "SELECT user_id FROM project_member WHERE project_id='" + projectId + "'");
        //按名字查询
        if (StringUtils.isNotEmpty(inputParam.getName())) {
            userQueryWrapper.like("name_", inputParam.getName());
        }
        userQueryWrapper.orderByAsc("order_num");//按时间排序
        //分页查询
        Page<BaseUser> result = userService.page(new Page<BaseUser>(
                inputParam.getPage(),
                inputParam.getSize()), userQueryWrapper);
        List<BaseUser> userList = result.getRecords();
        List<String> userIds = new ArrayList<>();//当前页所有用户id
        for (int i = 0; i < userList.size(); i++) {
            userIds.add(userList.get(i).getId());
        }
        long total = result.getTotal();
        //查询指定用户指定日期所有任务
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("work_date", workDate);
        if (userIds.size() > 0) {
            qw.in("user_id", userIds.toArray());
        } else {
            qw.isNull("user_id");
        }
        //是否只查询与当前项目相关
        if (inputParam.getProjectAboutOnly() == true) {
            qw.eq("project_id", projectId);
        }
//        qw.eq("type", PersonalPlan.TYPE_PROJECT);
        //排序
        qw.orderByAsc("start_time");
        qw.orderByDesc("complete_time");
        List<PersonalPlan> personalPlanList = this.list(qw);
        //给领导派发类型任务添加领导信息
        leaderPlanAddLeader(personalPlanList);
        //归类任务数据到用户
        for (int j = 0; j < personalPlanList.size(); j++) {
            PersonalPlan personalPlan = personalPlanList.get(j);
            for (int i = 0; i < userList.size(); i++) {
                BaseUser user = userList.get(i);
                if (user.getId().equals(personalPlan.getUserId())) {//任务归类到用户
                    user.getPersonalPlanList().add(personalPlan);
                    break;
                }
            }
        }
        //返回结果
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", userList);
        map.put("total", total);
        map.put("code", 1);
        return map;
    }

    /**
     * 查询部门及子部门所有用户每人每日的所有任务
     *
     * @param departIds
     * @param workDate
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> getDepartmentDailyTable(String departIds, LocalDate workDate, InputParam inputParam) {
        //拼接部门id为sql参数
        String[] idArr = departIds.split(",");
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < idArr.length; i++) {
            idList.add("'" + idArr[i] + "'");
        }
        departIds = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
        //查询部门相关用户
        QueryWrapper<BaseUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.inSql("id_", "SELECT user_id FROM base_department_user WHERE depart_id IN(" + departIds + ")");
        if (StringUtils.isNotEmpty(inputParam.getName())) {
            userQueryWrapper.like("name_", inputParam.getName());
        }
        //账号在用状态
        userQueryWrapper.eq("status_", 1);
        //忽略某些人
        userQueryWrapper.notIn("id_", SysUtil.EXCLUDE_USERS);
        userQueryWrapper.orderByAsc("order_num");//按时间排序
        //分页查询
        Page<BaseUser> result = userService.page(new Page<BaseUser>(
                inputParam.getPage(),
                inputParam.getSize()), userQueryWrapper);
        List<BaseUser> userList = result.getRecords();
        List<String> userIds = new ArrayList<>();//当前页所有用户id
        for (int i = 0; i < userList.size(); i++) {
            userIds.add(userList.get(i).getId());
        }
        long total = result.getTotal();
        //查询指定用户指定日期所有任务
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("work_date", workDate);
        if (userIds.size() > 0) {
            qw.in("user_id", userIds.toArray());
        } else {
            qw.isNull("user_id");
        }
        //排序
        qw.orderByAsc("start_time");
        qw.orderByDesc("complete_time");
        List<PersonalPlan> personalPlanList = this.list(qw);
        //给领导派发类型任务添加领导信息
        leaderPlanAddLeader(personalPlanList);
        //归类任务数据到用户
        for (int j = 0; j < personalPlanList.size(); j++) {
            PersonalPlan personalPlan = personalPlanList.get(j);
            for (int i = 0; i < userList.size(); i++) {
                BaseUser user = userList.get(i);
                if (user.getId().equals(personalPlan.getUserId())) {//任务归类到用户
                    user.getPersonalPlanList().add(personalPlan);
                    break;
                }
            }
        }
        //返回结果
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", userList);
        map.put("total", total);
        map.put("code", 1);
        return map;
    }

    /**
     * 查询指定用户一周内任务
     *
     * @param userId   用户id
     * @param workDate 某周日期
     * @return
     */
    @Override
    public Map<String, Object> getPersonalPlanByWeek(String userId, String projectId, LocalDate workDate, Boolean secondWeek) {
        //没有指定用户则查询当前用户
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        //没有指定日期则查询当前日期
        if (workDate == null) {
            workDate = LocalDate.now();
        }
        List<Map<String, Object>> data = new ArrayList<>();
        //获取当前周每日对象
        int index = workDate.getDayOfWeek().getValue();//当前周几
        for (int i = index - 1; i > 0; i--) {//前几天
            Map<String, Object> map = new HashMap<>();
            map.put("workDate", workDate.minusDays(i));
            data.add(map);
        }
        //当天
        Map<String, Object> temp = new HashMap<>();
        temp.put("workDate", workDate);
        data.add(temp);
        //后几天
        int day = 7;

        if (secondWeek && secondWeek != null) {
            day = 14;
        }

        for (int i = 1; i <= (day - index); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("workDate", workDate.plusDays(i));
            data.add(map);
        }
        //查询每个日期用户对应的计划
        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> map = data.get(i);
            QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
            qw.eq("user_id", userId);
            qw.eq("work_date", map.get("workDate"));
            if (StringUtils.isNotEmpty(projectId)) {
                qw.eq("project_id", projectId);

            }
            //领导分配任务添加领导信息
            List<PersonalPlan> personalPlanList = this.list(qw);
            leaderPlanAddLeader(personalPlanList);
            map.put("personalPlanList", personalPlanList);
        }
        //返回结果
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", data);
        map.put("code", 1);
        return map;
    }

    /**
     * 给领导派发任务添加领导信息
     *
     * @param personalPlanList
     */
    public void leaderPlanAddLeader(List<PersonalPlan> personalPlanList) {
        for (int j = 0; j < personalPlanList.size(); j++) {
            PersonalPlan personalPlan = personalPlanList.get(j);
            //是领导派发任务
            if (!personalPlan.getUserId().equals(personalPlan.getCreatorId())) {
                BaseUser leader = userService.getById(personalPlan.getCreatorId());
                personalPlan.setCreator(leader);
            }
        }
    }


    @Override
    public Map<String, Object> addOrUpdate(PersonalPlan personalPlan) {
//        if (personalPlan.getWorkDate() == null) {
//            return ResponseInfo.error("错误的参数");
//        }
        //不是默认设置项目类型和空闲的时候，验证计划类型数据
        if (SysUtil.PLAN_TYPE_MAP.get(personalPlan.getType()) == null
                && personalPlan.getIsFree() == false
                && StringUtils.isEmpty(personalPlan.getProjectId())) {
            return ResponseInfo.error("错误的参数");
        }

        if (!StringUtil.iszNull(personalPlan.getOldId()) && !personalPlan.getId().equals(personalPlan.getOldId())) {
            personalPlan.setId(personalPlan.getOldId());
            return edit(personalPlan);
        }

        //没有主键，新增
        if (StringUtils.isEmpty(personalPlan.getId())) {
            //只有经理，总经理，老板，管理员有权限新增编辑删除
//            boolean flag = hasEditAblePermission();
//            if (flag == false && StringUtils.isNotEmpty(personalPlan.getUserId()) && StringUtils.isEmpty(personalPlan.getProjectId())) {//是帮别人添加，并且没权限,非项目类型
//                return ResponseInfo.error("当前账号无权限，必须是自身账户或【经理，总经理，老板，管理员】角色账户");
//            }

            return add(personalPlan);
        } else {
            //已完成计划不可编辑
            PersonalPlan temp = this.getById(personalPlan.getId());
            if (temp == null) {
                return add(personalPlan);
            }
            if (temp.getState() == PersonalPlan.STATE_COMPLETE) {
                return ResponseInfo.error("已完成计划不可编辑");
            }
            //只有经理，总经理，老板，管理员有权限新增编辑删除
//            boolean flag = hasEditAblePermission();
//            if (flag == false && !temp.getUserId().equals(SysUtil.getLoginUserId(request)) && StringUtils.isEmpty(personalPlan.getProjectId())) {//是帮别人添加，并且没权限,非项目类型
//                return ResponseInfo.error("当前账号无权限，必须是自身账户或【经理，总经理，老板，管理员】角色账户");
//            }
            //编辑
            return edit(personalPlan);
        }
    }

    /**
     * 判断当前用户是否拥有编辑权限
     *
     * @return
     */
    private boolean hasEditAblePermission() {
        //只有经理，总经理，老板，管理员,超级管理员有权限新增编辑删除
        String[] roles = new String[]{SysUtil.ROLE_FLAG_JL, SysUtil.ROLE_FLAG_ZJL, SysUtil.ROLE_FLAG_BOSS, SysUtil.ROLE_FLAG_ADMIN};
        //上级领导
        return roleService.hasRoles(roles, SysUtil.getLoginUserId(request));
    }

    /**
     * 删除
     *
     * @param id
     * @param isCompleteDel 完成状态是否运行删除
     * @return
     */
    @Override
    public Map<String, Object> dele(String id, boolean isCompleteDel) {
        //已完成计划不可删除
        PersonalPlan temp = this.getById(id);
        if (temp.getState() == PersonalPlan.STATE_COMPLETE && isCompleteDel == false) {
            throw new RuntimeException("已完成计划不可删除");
        }
        //-------------------------add by yj start-------------------------------//
        //超过两天的不能删除
        if (temp.getWorkDate() != null) {
            long between = DAYS.between(temp.getWorkDate(), LocalDate.now());
            if (between > 2) {
                return ResponseInfo.error("超过两天的不可以删除");
            }
        }
        //-------------------------add by yj end-------------------------------//
//        boolean flag = hasEditAblePermission();
//        if (flag == false && !SysUtil.getLoginUserId(request).equals(temp.getUserId()) && StringUtils.isEmpty(temp.getProjectId())) {//是帮别人添加，并且没权限
//            throw new RuntimeException("当前账号无权限，必须是自身账户或【经理，总经理，老板，管理员】角色账户");
//        }
        String loginUserId = SysUtil.getLoginUserId(request);//计划创建者
//        if (flag == false && !loginUserId.equals(temp.getUserId()) && PersonalPlan.TYPE_PROJECT == temp.getType()) {//删除别人的项目类型个人计划
        QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUserId);//指定项目id
        queryWrapper.eq("project_id", temp.getProjectId());//指定项目id
        queryWrapper.eq("identity_type", 0);//指定项目id
        long count = projectMemberService.count(queryWrapper);
//            if (count == 0) {
//                throw new RuntimeException("当前账号不是指定项目负责人，无权删除计划");
//            }
//        }

        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("id", id);

        PersonalPlan byId = this.getById(id);
        this.baseMapper.deleteById(id);
        baseLogsService.log("全员计划", "删除", byId.getTitle(), byId, id, byId.getWorkDate(), byId.getUserId());
        SendMessage(byId, "删除");
        topicMessageService.deleteByTopicId(id);
        attachmentListService.deleteByTargetId(id);//删除关联附件
        return ResponseInfo.success();
    }

    /**
     * 切换当前计划状态
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public Map<String, Object> stateChange(String id, Integer state) {
        PersonalPlan personalPlan = this.getById(id);
        if (personalPlan == null) {
            return ResponseInfo.error("错误的参数");
        }
        if (state != PersonalPlan.STATE_COMPLETE && state != PersonalPlan.STATE_UNCOMPLETED) {
            return ResponseInfo.error("错误的参数");
        }
        if (personalPlan.getState() == state) {
            return ResponseInfo.error("状态已改变");
        }
        boolean flag = hasEditAblePermission();
        if (flag == false && !SysUtil.getLoginUserId(request).equals(personalPlan.getUserId())) {//是帮别人添加，并且没权限
            return ResponseInfo.error("当前账号无权限，必须是自身账户或【经理，总经理，老板，管理员】角色账户");
        }
        UpdateWrapper<PersonalPlan> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("state", state);
        if (state == PersonalPlan.STATE_UNCOMPLETED) {
            updateWrapper.set("complete_time", null);
        } else if (state == PersonalPlan.STATE_COMPLETE) {
            updateWrapper.set("complete_time", LocalDateTime.now());
        }
        this.update(updateWrapper);
        return ResponseInfo.success();
    }

    /**
     * 当天已使用时间段
     *
     * @param userId   指定用户
     * @param workDate 指定时间
     * @return
     */
    @Override
    public Map<String, Object> getUsedTime(String userId, LocalDate workDate) {
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        QueryWrapper<PersonalPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_date", workDate);
        queryWrapper.eq("user_id", userId);
        List<PersonalPlan> list = this.list(queryWrapper);
        List<String> usedTimeList = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
        for (int i = 0; i < list.size(); i++) {
            PersonalPlan plan = list.get(i);
            String usedTime = plan.getStartTime().format(df) + "-" + plan.getEndTime().format(df);
            usedTimeList.add(usedTime);
        }
        return ResponseInfo.success(usedTimeList);
    }

    /**
     * 删除指定日期指定时间段任务
     *
     * @param userId
     * @param workDate
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Map<String, Object> deleAll(String userId, LocalDate workDate, LocalTime startTime, LocalTime endTime) {
        //只有经理，总经理，老板，管理员有权限新增编辑删除
//        boolean flag = hasEditAblePermission();
//        if (flag == false && StringUtils.isNotEmpty(userId)) {//是帮别人添加，并且没权限
//            return ResponseInfo.error("当前账号无权限，必须是自身账户或【经理，总经理，老板，管理员】角色账户");
//        }
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.eq("work_date", workDate);
        qw.ge("start_time", startTime);
        qw.le("end_time", endTime);
        qw.eq("state", 0);//未完成任务
        List<PersonalPlan> list = this.list(qw);

        for (int i = 0; i < list.size(); i++) {
            PersonalPlan plan = list.get(i);
            this.dele(plan.getId(), false);
        }
        return ResponseInfo.success();
    }

    /**
     * 删除指定日期任务
     *
     * @param userId
     * @param workDate
     * @return
     */
    @Override
    public Map<String, Object> deleAllDay(String userId, LocalDate workDate) {
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.eq("work_date", workDate);
//        qw.eq("state",0);//未完成任务
        List<PersonalPlan> list = this.list(qw);

        for (int i = 0; i < list.size(); i++) {
            PersonalPlan plan = list.get(i);
            this.dele(plan.getId(), true);
        }
        return ResponseInfo.success();
    }

    /**
     * 完成指定日期指定时间段任务
     *
     * @param userId
     * @param workDate
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Map<String, Object> completeAll(String userId, LocalDate workDate, LocalTime startTime, LocalTime endTime) {
        UpdateWrapper<PersonalPlan> uw = new UpdateWrapper<>();
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        uw.eq("user_id", userId);
        uw.eq("work_date", workDate);
        uw.ge("start_time", startTime);
        uw.le("end_time", endTime);
        uw.eq("state", 0);//未完成任务
        uw.set("state", PersonalPlan.STATE_COMPLETE);//设置状态完成
        uw.set("complete_time", LocalDateTime.now());//设置完成时间
        this.update(uw);
        return ResponseInfo.success();
    }

    /**
     * 获取个人计划统计数据
     *
     * @param inputParam name 用户姓名
     * @param inputParam id 部门id
     * @param startDate  开始日期
     * @param endDate    结束日期
     * @return
     */
    @Override
    public Map<String, Object> statisticalByUser(LocalDate startDate, LocalDate endDate, InputParam inputParam) {
        //特殊处理，若部门id存在，则改成in查询
        if (org.apache.commons.lang.StringUtils.isNotEmpty(inputParam.getId())) {
            String temp = " (";
            String[] idArr = inputParam.getId().split(",");
            List<String> idList = new ArrayList<>();
            for (int i = 0; i < idArr.length; i++) {
                idList.add("'" + idArr[i] + "'");
            }
            String idtemp = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
            temp += idtemp + ") ";
            inputParam.setId(temp);
        }
        //排除被设置忽略的人
        String[] ignorUserIds = (String[]) configService.getPlanStatisticalIgnoreUserConfig().get("data");
        inputParam.setIgnorUserIds(ignorUserIds);

        if (inputParam.getPage() == null || inputParam.getSize() == null) {
            return ResponseInfo.error("参数错误");
        }
        inputParam.setOffset((inputParam.getPage() - 1) * inputParam.getSize());
        //安装部门分页查询相关用户信息
        List<BaseUser> list = userDao.getUsersByDepart(inputParam);
        //查询每个用户的个人任务分类统计数据
        Map<String, Object> map = getPlanCountDataMap(startDate, endDate, list);
        map.put("total", userDao.totalUsersByDepart(inputParam));
        map.put("code", 1);
        return map;
    }

    /**
     * 查询每个用户的个人任务分类统计数据
     *
     * @param startDate
     * @param endDate
     * @param list
     * @return
     */
    public Map<String, Object> getPlanCountDataMap(LocalDate startDate, LocalDate endDate, List<BaseUser> list) {
        //查询每个用户的个人任务分类统计数据
        String[] xData = new String[list.size()];//保存坐标数据
        int[] dailyData = new int[list.size()];//日常任务数数组
        int[] projectData = new int[list.size()];//项目任务数数组
        int[] otherData = new int[list.size()];//额外任务数数组
        int[] askForLeaveData = new int[list.size()];//请假任务数数组
        int[] businessData = new int[list.size()];//专属任务数数组
        int[] freeData = new int[list.size()];//空闲任务数数组
        for (int i = 0; i < list.size(); i++) {
            BaseUser user = list.get(i);
            xData[i] = user.getName();
            int dailyNum = getPlanNumByUser(startDate, endDate, user.getId(), PersonalPlan.TYPE_PERSONAL);//日常任务数
            int projectNum = getPlanNumByUser(startDate, endDate, user.getId(), PersonalPlan.TYPE_PROJECT);//项目任务数
            int otherNum = getPlanNumByUser(startDate, endDate, user.getId(), PersonalPlan.TYPE_ADDITIONAL);//额外任务数
            int askForLeaveNum = getPlanNumByUser(startDate, endDate, user.getId(), PersonalPlan.TYPE_ASK_FOR_LEAVE);//请假任务数
            int businessNum = getPlanNumByUser(startDate, endDate, user.getId(), PersonalPlan.TYPE_BUSINESS);//请假任务数
            dailyData[i] = dailyNum;
            projectData[i] = projectNum;
            otherData[i] = otherNum;
            askForLeaveData[i] = askForLeaveNum;
            businessData[i] = businessNum;
            int day = (int) (DAYS.between(startDate, endDate) + 1);
            int total = day * PersonalPlan.TIME_NUM;
            freeData[i] = total - dailyNum - projectNum - otherNum - askForLeaveNum - businessNum;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("xData", xData);
        map.put("dailyData", dailyData);
        map.put("projectData", projectData);
        map.put("otherData", otherData);
        map.put("freeData", freeData);
        map.put("askForLeaveData", askForLeaveData);
        map.put("businessData", businessData);
        return map;
    }

    /**
     * 查询每个用户业务专属计划站点统计数据
     *
     * @param startDate
     * @param endDate
     * @param list
     * @return
     */
    public Map<String, Object> getBusinessSitePlanCountDataMap(LocalDate startDate, LocalDate endDate, List<BaseUser> list) {
        //查询每个用户的个人任务分类统计数据
        String[] xData = new String[list.size()];//保存坐标数据
        int[] businessNumData = new int[list.size()];//专属任务数数组
        List<PersonalPlan>[] businessData = new List[list.size()];//专属任务数数组
        for (int i = 0; i < list.size(); i++) {
            BaseUser user = list.get(i);
            xData[i] = user.getName();
            QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
            qw.eq("user_id", user.getId());//用户id
            //工作时间大于等于开始日期，小于等于结束日期
            qw.le("work_date", endDate);
            qw.ge("work_date", startDate);
            qw.eq("type", PersonalPlan.TYPE_BUSINESS);//查询业务专属
            List<PersonalPlan> planList = this.list(qw);
            businessNumData[i] = planList.size();
            businessData[i] = planList;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("xData", xData);
        map.put("businessNumData", businessNumData);
        map.put("businessData", businessData);
        map.put("siteData", SysUtil.PLAN_YWTYPE_LIST);//所有站点信息
        return map;
    }

    /**
     * 获取关注的人的个人计划统计数据
     *
     * @param inputParam name 用户姓名
     * @param startDate  开始日期
     * @param endDate    结束日期
     * @return
     */
    @Override
    public Map<String, Object> statisticalByFollowUser(String groupId, LocalDate startDate, LocalDate endDate, InputParam inputParam) {
        String userId = SysUtil.getLoginUserId(request);//当前登录用户id
        //查询项目相关用户
        QueryWrapper<BaseUser> userQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(groupId)) {
            userQueryWrapper.inSql("id_", "SELECT follow_user_id FROM user_follow_list WHERE group_id='" + groupId + "' and  user_id='" + userId + "'");
        } else {
            userQueryWrapper.inSql("id_", "SELECT follow_user_id FROM user_follow_list WHERE user_id='" + userId + "'");
        }
        //按名字查询
        if (StringUtils.isNotEmpty(inputParam.getName())) {
            userQueryWrapper.like("name_", inputParam.getName());
        }
        //排除被设置忽略的人
        String[] ignorUserIds = (String[]) configService.getPlanStatisticalIgnoreUserConfig().get("data");
        if (ignorUserIds != null && ignorUserIds.length > 0) {
            userQueryWrapper.notIn("id_", ignorUserIds);
        }
        userQueryWrapper.orderByAsc("order_num");
        //分页查询
        Page<BaseUser> result = userService.page(new Page<BaseUser>(
                inputParam.getPage(),
                inputParam.getSize()), userQueryWrapper);
        List<BaseUser> list = result.getRecords();
        //查询每个用户的个人任务分类统计数据
        Map<String, Object> map = getPlanCountDataMap(startDate, endDate, list);
        map.put("total", result.getTotal());
        map.put("code", 1);
        return map;
    }

    /**
     * 获取站点统计数据
     *
     * @param inputParam name 用户姓名
     * @param inputParam id 部门id
     * @param startDate  开始日期
     * @param endDate    结束日期
     * @return
     */
    @Override
    public Map<String, Object> statisticalSiteByUser(LocalDate startDate, LocalDate endDate, InputParam inputParam) {
        String temp = " (";
        List<String> idList = new ArrayList<>();
        //特殊处理，若部门id存在，则改成in查询
        if (org.apache.commons.lang.StringUtils.isNotEmpty(inputParam.getId())) {
            String[] idArr = inputParam.getId().split(",");
            for (int i = 0; i < idArr.length; i++) {
                idList.add("'" + idArr[i] + "'");
            }
        } else {
            //如果没有指定部门id,则查询指定部门
            List<BaseDepartment> list = (List<BaseDepartment>) departmentService.getBusinessSiteDepart().get("data");
            for (int i = 0; i < list.size(); i++) {
                idList.add("'" + list.get(i).getId() + "'");
            }
        }
        String idtemp = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
        temp += idtemp + ") ";
        inputParam.setId(temp);
//        System.out.println("选择的部门id:"+idList);
        //排除被设置忽略的人
        String[] ignorUserIds = (String[]) configService.getPlanStatisticalIgnoreUserConfig().get("data");
        inputParam.setIgnorUserIds(ignorUserIds);

        if (inputParam.getPage() == null || inputParam.getSize() == null) {
            return ResponseInfo.error("参数错误");
        }
        inputParam.setOffset((inputParam.getPage() - 1) * inputParam.getSize());
        //安装部门分页查询相关用户信息
        List<BaseUser> list = userDao.getUsersByDepart(inputParam);
        //查询每个用户的个人任务分类统计数据
        Map<String, Object> map = getBusinessSitePlanCountDataMap(startDate, endDate, list);
        map.put("total", userDao.totalUsersByDepart(inputParam));
        map.put("code", 1);
        return map;
    }

    /**
     * 根据条件查询用户对应类型的计划个数
     *
     * @param startDate
     * @param endDate
     * @param userId
     * @param type
     * @return
     */
    @Override
    public int getPlanNumByUser(LocalDate startDate, LocalDate endDate, String userId, Integer type) {
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);//用户id
        //工作时间大于等于开始日期，小于等于结束日期
        qw.le("work_date", endDate);
        qw.ge("work_date", startDate);
        qw.eq("type", type);//查询个人
        int num = this.count(qw);//个人数量
        return num;
    }


    /**
     * 新增计划
     *
     * @param personalPlan
     * @return
     */
    private Map<String, Object> add(PersonalPlan personalPlan) {
        if (personalPlan.getReplyState() != null && personalPlan.getReplyState() == 1) {
            personalPlan.setSelectTimeList(personalPlan.getStartTime() + "-" + personalPlan.getEndTime());
            personalPlan.setSelectDayList(String.valueOf(personalPlan.getWorkDate()));
        }
        if (StringUtils.isEmpty(personalPlan.getSelectTimeList())) {
            return ResponseInfo.error("请选择计划时间段");
        }
        if (StringUtils.isEmpty(personalPlan.getSelectDayList())) {
            return ResponseInfo.error("请选择计划日期");
        }
        //只有经理，总经理，老板，管理员有权限新增编辑删除
//        boolean flag = hasEditAblePermission();
        String creatorId = SysUtil.getLoginUserId(request);//计划创建者
        String userId = personalPlan.getUserId();//计划执行人

        //如果有指定项目id,则类型为项目否则为，type前端传递了
        if (PersonalPlan.TYPE_PROJECT == personalPlan.getType()) {
            if (StringUtils.isEmpty(personalPlan.getProjectId())) {
                return ResponseInfo.error("项目不可为空");
            } else {
                //查询项目数据
                personalPlan.setProjectPlan(projectPlanService.getById(personalPlan.getProjectId()));
            }
//            if (StringUtils.isNotEmpty(userId) && !creatorId.equals(userId) && flag == false) {//如果有指定计划执行人，并且不是计划创建人，那么计划创建者必须是项目负责人
            QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", creatorId);//指定项目id
            queryWrapper.eq("project_id", personalPlan.getProjectId());//指定项目id
            queryWrapper.eq("identity_type", 0);//指定项目id
//                long count = projectMemberService.count(queryWrapper);
//                if (count == 0) {
//                    return ResponseInfo.error("当前账号不是指定项目负责人，无权分配计划");
//                }
//            }
        }
        personalPlan.setState(PersonalPlan.STATE_UNCOMPLETED);//状态未完成
        //如果未指定计划所属用户，则默认是当前用户执行,创建者也是当前用户
        if (StringUtils.isEmpty(userId)) {
            personalPlan.setUserId(creatorId);
        }
        //计划创建者是当前用户
        personalPlan.setCreatorId(creatorId);
        personalPlan.setCreateTime(LocalDateTime.now());
        //给每个时间段添加计划
        String[] selectTimeList = personalPlan.getSelectTimeList().split(",");
        String[] selectDayList = personalPlan.getSelectDayList().split(",");
        for (int i = 0; i < selectTimeList.length; i++) {
            //给每个日期添加计划
            for (int j = 0; j < selectDayList.length; j++) {
                //设置日期
                personalPlan.setWorkDate(LocalDate.parse(selectDayList[j]));
                LocalDate start = personalPlan.getWorkDate();
                LocalDate end = LocalDate.now();
                Period next = Period.between(start, end);
                int days = next.getDays();//相差天数
                if (days > UNMODIFY) {
                    return ResponseInfo.error("超过两天不可新增");
                }
                //如果是项目类型，如果日期不在项目时间内，跳过
                if (PersonalPlan.TYPE_PROJECT == personalPlan.getType()) {
                    LocalDate startDate = personalPlan.getProjectPlan().getStartTime();
                    LocalDate endDate = personalPlan.getProjectPlan().getEndTime();
                    //计划日期在开始日期前，结束日期后
                    if (endDate.isBefore(personalPlan.getWorkDate()) || startDate.isAfter(personalPlan.getWorkDate())) {
                        continue;//跳过
                    }

                }
                String[] selectTime = selectTimeList[i].split("-");
                //查询日期时段如果已添加，不重复添加
                QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
                qw.eq("work_date", personalPlan.getWorkDate());
                qw.eq("user_id", personalPlan.getUserId());
                qw.eq("start_time", LocalTime.parse(selectTime[0]));
                int count = this.count(qw);
                if (count > 0) {
                    continue;//跳过
                }
                //设置时间参数
                if (personalPlan.getReplyState() == null) {
                    personalPlan.setId(SysUtil.UUID());//设置主键
                }
                personalPlan.setStartTime(LocalTime.parse(selectTime[0]));//设置开始时间
                personalPlan.setEndTime(LocalTime.parse(selectTime[1]));//设置开始时间
                //保存
                this.save(personalPlan);
                baseLogsService.log(personalPlan.getModule(), "增加", personalPlan.getTitle(), personalPlan, personalPlan.getId(), personalPlan.getWorkDate(), personalPlan.getUserId());
                SendMessage(personalPlan, "增加");
            }
        }
        return ResponseInfo.success();

    }

    /**
     * 更新计划
     *
     * @param personalPlan
     * @return
     */
    private Map<String, Object> edit(PersonalPlan personalPlan) {
        System.out.println(personalPlan);
        LocalDate start = personalPlan.getWorkDate();
        LocalDate end = LocalDate.now();
        Period next = Period.between(start, end);
        int days = next.getDays();//相差天数
        if (days > UNMODIFY) {
            return ResponseInfo.error("超过两天不可修改");
        }
        //只有经理，总经理，老板，管理员有权限新增编辑删除
//        boolean flag = hasEditAblePermission();
        String creatorId = SysUtil.getLoginUserId(request);//计划创建者
        String userId = personalPlan.getUserId();//计划执行人
        UpdateWrapper<PersonalPlan> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("title", personalPlan.getTitle());
        updateWrapper.set("remark", personalPlan.getRemark());
        updateWrapper.set("content", personalPlan.getContent());//设置工作内容
        updateWrapper.set("type", personalPlan.getType());//设置工作内容
        //如果修改为项目类型
        if (PersonalPlan.TYPE_PROJECT.equals(personalPlan.getType())) {
            if (StringUtils.isEmpty(personalPlan.getProjectId())) {
                return ResponseInfo.error("项目不可为空");
            }
            updateWrapper.set("project_id", personalPlan.getProjectId());//设置项目计划id
//            if (StringUtils.isNotEmpty(userId) && !creatorId.equals(userId) && flag == false) {//如果有指定计划执行人，并且不是计划创建人，那么计划创建者必须是项目负责人
            QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", creatorId);//指定项目id
            queryWrapper.eq("project_id", personalPlan.getProjectId());//指定项目id
            queryWrapper.eq("identity_type", 0);//指定项目id
//                long count = projectMemberService.count(queryWrapper);
//                if (count == 0) {
//                    return ResponseInfo.error("当前账号不是指定项目负责人，无权分配计划");
//                }
//            }
        } else {
            //其他类型设置项目为空
            updateWrapper.set("project_id", null);//设置项目计划id
        }

//        if (flag || PersonalPlan.TYPE_PROJECT == personalPlan.getType()) {
//            updateWrapper.set("creator_id", creatorId);//修改创建者为领导
//        }

        updateWrapper.eq("id", personalPlan.getId());
        this.update(updateWrapper);
        baseLogsService.log(personalPlan.getModule(), "修改", personalPlan.getTitle(), personalPlan, personalPlan.getId(), personalPlan.getWorkDate(), personalPlan.getUserId());
        SendMessage(personalPlan, "修改");
        return ResponseInfo.success();
    }

    /**
     * 获取当天未完成任务
     *
     * @return
     */
    @Override
    public Map<String, Object> getTodayUndoPlan() {
        String userId = SysUtil.getLoginUserId(request);
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);//用户id
        qw.eq("work_date", LocalDate.now());   //当天时间
        qw.le("end_time", LocalTime.now());//当前时间
        qw.eq("state", PersonalPlan.STATE_UNCOMPLETED);//未完成任务
        int total = this.count(qw);
        return ResponseInfo.success(total);
    }

    @Override
    public Map<String, Object> completeByPlanIds(String planIds) {
//        String userId = SysUtil.getLoginUserId(request);
        String[] idArr = planIds.split(",");
        UpdateWrapper<PersonalPlan> uw = new UpdateWrapper<>();
//        if (StringUtils.isEmpty(userId)) {
//            userId = SysUtil.getLoginUserId(request);
//        }
//        uw.eq("user_id", userId);
        uw.eq("state", PersonalPlan.STATE_UNCOMPLETED);//未完成任务
        uw.in("id", idArr);
        uw.set("state", PersonalPlan.STATE_COMPLETE);//设置状态完成
        uw.set("complete_time", LocalDateTime.now());//设置完成时间
        this.update(uw);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> uncompleteByPlanIds(String planIds) {
//        String userId = SysUtil.getLoginUserId(request);
        String[] idArr = planIds.split(",");
        UpdateWrapper<PersonalPlan> uw = new UpdateWrapper<>();
//        uw.eq("user_id", userId);
        uw.eq("state", PersonalPlan.STATE_COMPLETE);//已完成任务
        uw.in("id", idArr);
        uw.set("state", PersonalPlan.STATE_UNCOMPLETED);//设置状态完成
        uw.set("complete_time", null);//设置完成时间
        this.update(uw);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> deleByPlanIds(String planIds) {
        String[] idArr = planIds.split(",");
        List<String> idList = Arrays.asList(idArr);
        for (String personalId :
                idList) {
            PersonalPlan pp = this.getById(personalId);
            //-------------------------add by yj start-------------------------------//
            //超过两天的不能删除
            if (pp.getWorkDate() != null) {
                long between = DAYS.between(pp.getWorkDate(), LocalDate.now());
                if (between > 2) {
                    return ResponseInfo.error("超过两天的不可以删除");
                }
            }
            //-------------------------add by yj end-------------------------------//
        }

        this.baseMapper.deleteBatchIds(idList);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> editByPlanIds(PersonalPlan personalPlan, String planIds) {
        if (StringUtils.isEmpty(planIds)) {
            return ResponseInfo.error("参数错误");
        }
        String idArr[] = planIds.split(",");
        List<PersonalPlan> userList = new ArrayList<>();

        for (String s : idArr) {
            PersonalPlan plan = this.getById(s);
            userList.add(plan);
            LocalDate start = plan.getWorkDate();
            LocalDate end = LocalDate.now();
            Period next = Period.between(start, end);
            int days = next.getDays();//相差天数
            if (days > UNMODIFY) {
                return ResponseInfo.error("超过两天不可修改");
            }
        }

        String creatorId = SysUtil.getLoginUserId(request);//计划创建者
        UpdateWrapper<PersonalPlan> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("type", personalPlan.getType());
        if (PersonalPlan.TYPE_PROJECT.equals(personalPlan.getType())) {

            if (StringUtils.isEmpty(personalPlan.getProjectId())) {
                return ResponseInfo.error("项目不可为空");
            } else {
                updateWrapper.set("project_id", personalPlan.getProjectId());
            }
        } else {
            updateWrapper.set("project_id", null);
        }
        updateWrapper.set("title", personalPlan.getTitle());
        updateWrapper.set("remark", personalPlan.getRemark());
        updateWrapper.set("content", personalPlan.getContent());//设置工作内容
        updateWrapper.eq("state", 0);//未完成的才可以修改
//        updateWrapper.eq("creator_id", creatorId);
        updateWrapper.in("id", idArr);
        this.update(updateWrapper);

        userList.forEach(item -> {
            item.setModule(personalPlan.getModule());
            item.setTitle(personalPlan.getTitle());
            item.setContent(personalPlan.getContent());
            item.setRemark(personalPlan.getRemark());
            item.setType(personalPlan.getType());
            baseLogsService.log(item.getModule(), "修改", item.getTitle(), item, item.getId(), item.getWorkDate(), item.getUserId());
            SendMessage(item, "修改");
        });

        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> getPlanByProId(InputParam inputParam) {
        if (StringUtils.isEmpty(inputParam.getProject()) || StringUtils.isEmpty(inputParam.getCurUserId())) {
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
        qw.eq("type", 1);
        qw.eq("project_id", inputParam.getProject());
        qw.eq("creator_id", inputParam.getCurUserId());
        //排序
        qw.orderByDesc("work_date", "end_time");
        //分页查询
        Page<PersonalPlan> result = this.page(new Page<PersonalPlan>(
                inputParam.getPage(),
                inputParam.getSize()), qw);
        List<PersonalPlan> personalPlans = result.getRecords();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", personalPlans);
        map.put("total", result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public ResponseBean<String> changeWeek(InputParam inputParam) {
        DateEasy da = new DateEasy();
        String res = "";
        if ("nowWeek".equals(inputParam.getName())) {
            res = da.toYYYYhMMhDD();
        } else if ("preWeek".equals(inputParam.getName())) {
            da.addDate(-7);
            res = da.toYYYYhMMhDD();
        } else if ("nextWeek".equals(inputParam.getName())) {
            da.addDate(7);
            res = da.toYYYYhMMhDD();
        } else {
            return ResponseBean.error("参数错误");
        }
        return ResponseBean.success(res);
    }

    public void SendMessage(PersonalPlan personalPlan, String handle) {
        Map<String, Object> byIdList = baseLogsService.getByIdList(personalPlan.getId());
        List<BaseLogs> list = (List<BaseLogs>) byIdList.get("rows");
        Set<String> set = new HashSet<>();
        list.forEach(item -> {
            set.add(item.getUserId());
            set.add(item.getSetUserId());
        });
        String UserId = SysUtil.getLoginUserId(request);
        for (String user_id : set) {
            if (!user_id.equals(UserId)) {
                TopicMessage topicMessage = new TopicMessage();
                topicMessage.setContent(personalPlan.getModule() + handle + "," + handle + "位置:" + personalPlan.getWorkDate() + "(时间段:" + personalPlan.getStartTime() + "-" + personalPlan.getEndTime() + ")");
                topicMessage.setReplyUserId(user_id);
                topicMessage.setType(2);
                topicMessage.setTopicId(user_id + "-" + UserId);
                Map<String, Object> add = topicMessageService.add(topicMessage);
            }
        }
    }
}
